# Importing Data
CHINA <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Iran/China.xlsx")

# Checking the Imported Data
View(CHINA)

# Creating Time Series Data
CHINA_ts <- ts(CHINA, start=c(2005,1), end=c(2018,10), frequency=12)

# Viewing and Checking the Created Time Series Data
CHINA_ts
sum(is.na(CHINA_ts))
library(forecast)
CHINA_ts <- tsclean(CHINA_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(CHINA_ts)
plot(aggregate(CHINA_ts,FUN=mean))

# Decomposing
CHINA_ts_decomp <- decompose(CHINA_ts)
plot(CHINA_ts_decomp)

# Testing for Stationarity
acf(CHINA_ts, lag.max=20)
pacf(CHINA_ts, lag.max=20)

# To see any seasonal effect
boxplot(CHINA_ts~cycle(CHINA_ts))

# To remove trend effect
CHINA_ts_diff <- diff(CHINA_ts)
plot(CHINA_ts_diff)

# To remove variance effect
CHINA_ts_log <- log(CHINA_ts)
plot(CHINA_ts_log)

# To remove both (Trend and Variance) effects
CHINA_ts_both <- diff(log(CHINA_ts))
plot(CHINA_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(CHINA_ts, lag.max=20)
acf(log(CHINA_ts), lag.max=20)
acf(diff(CHINA_ts), lag.max=20)
acf(diff(log(CHINA_ts)), lag.max=20)
pacf(CHINA_ts, lag.max=20)
pacf(log(CHINA_ts), lag.max=20)
pacf(diff(CHINA_ts), lag.max=20)
pacf(diff(log(CHINA_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
CHINA_ts_model <- auto.arima(CHINA_ts)
CHINA_ts_model
CHINA_ts_model <- auto.arima(CHINA_ts, ic="aic", trace = TRUE)
CHINA_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(CHINA_ts_model$resid)
acf(CHINA_ts_model$residuals, main='ACF Residual')
pacf(CHINA_ts_model$residuals, main='ACF Residual')
Box.test(CHINA_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
CHINA_ts_forecast <- forecast (CHINA_ts_model, level=c(95), h=266)
plot(CHINA_ts_forecast)
CHINA_ts_forecast             



write.table(CHINA_ts_forecast, file="China_TSA.csv", sep=",")
